<?php

namespace app\admin\controller\lists;

use app\common\controller\Backend;
use think\Config;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\Loader;
use think\response\Json;

/**
 * 服务单录入查询需要的字段集合
 *
 * @icon fa fa-circle-o
 */
class Shenhes extends Backend
{

    /**
     * Shenhes模型对象
     * @var \app\admin\model\lists\Shenhes
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\lists\Shenhes;
        $this->view->assign("statusList", $this->model->getStatusList());
        $jigoudata = [''=>'请选择业务来源','直属业务'=>'直属业务','直接业务'=>'直接业务','分支机构'=>'分支机构','合作商'=>'合作商','查勘机构'=>'查勘机构','招商业务'=>'招商业务','合作业务 '=>'合作业务'];
        $this->view->assign('jigoudata', $jigoudata);
        $chexing = Config::get('site.chexing');
        $this->view->assign('chexing', $chexing);
        $xingzhi = Config::get('site.xingzhi');
        $this->view->assign('xingzhi', $xingzhi);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $where1['status'] = 3;
        $list = $this->model
            ->where($where)
            ->where($where1)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }
    /**
     * 浏览
     * @param $ids
     * @return void
     * @throws DbException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function details($ids = null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $admin = $this->auth->getUserInfo();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        $row['car_register'] = date('Y-m-d',$row['car_register']);
        $row['plan_strattime'] = date('Y-m-d H:i:s',$row['plan_strattime']);
        $row['plan_endtime'] = date('Y-m-d H:i:s',$row['plan_endtime']);

        $row['main_freess'] = bcmul(((100-floatval($row['feiyong']))/100),$row['main_free'],2);//净费
        $this->view->assign('row', $row);
        $select = selectMenus_zuzhi($admin['zuzhi']);
        $this->assign('selectMenu',$select);
        $ren = db('admin')->where('zuzhi','in',$row['yw_class'])->select();
        $this->assign('ren',$ren);
        $ying = db('tong_files')->where('tong_id',$ids)->select();
        $this->assign('file', $ying);
        $yijian = db('yijian')->where('did',$ids)->select();
        $this->assign('yijian',$yijian);
        $this->assign('admin',$admin);
        return $this->view->fetch();
    }

    //服务单 财务审核方法
    public function zuihou(){
        $id = $_POST['id'];
        if ($_POST['tong_number']==''){
            $data['did'] = $_POST['id'];
            $data['shen_time'] = strtotime($_POST['shenhe_time']);
            $data['shen_peo'] = $_POST['shenhe_peo'];
            $dataa['status'] = 5;
            $dataa['yw_shenhe_time'] = strtotime($_POST['shenhe_time']);
            $dataa['yw_finance_peo'] = $_POST['shenhe_peo'];
            $area_code = '0000';
            if ($_POST['shenhe_yijian'] == ''){
                $data['shen_yijian'] = '财务审核(服务单)通过';
            } else {
                $data['shen_yijian'] = $_POST['shenhe_yijian'];
            }
            $data['user_id'] = $this->auth->getUserInfo()['id'];
            Db::startTrans();
            try {
                $res = Db::name('yijian')->insert($data);
                $table = 'list_one';
                $field = 'tong_number';
                $prev = 'HZZX';
                $tong_number = $this->gen_tong_number($table, $field, $prev, $area_code);
                $dataa['tong_number'] = $tong_number;
                $dataa['pay_type'] = $_POST['feiyong_type'];
                if($dataa['pay_type'] == 2){
                    $dataa['pay_fangshi'] = $_POST['feiyong_qita'];
                }else{
                    $dataa['pay_fangshi'] = '对公';
                }
                $ress = Db::name('list_one')->where('id',$id)->update($dataa);
                if($res){
                    $this->saveFile($id,$_POST['file']);
                    Db::commit();
                    $this->success('操作成功');
                }else{
                    Db::rollback();
                    $this->error('操作失败');
                }
            }catch (Exception $e){
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
    }
    public function saveFile($id, $urls) {
        $newid = $id;
        $urls = explode(',', $urls);
        $count = count($urls);
        $res = false;
        for ($i=0;$i<$count;$i++){
            $img['url'] = $urls[$i];
            $img['tong_id'] = $newid;
            $img['title'] = '';
            $img['updatetime'] = time();
            $res = db('tong_files')->insert($img);
        }

        return $res;
    }

    private function gen_tong_number($table, $field, $prev, $area_code) {
        $tong_number = null;
        $year = date('Ymd', time());
        $next_key = 'next_'.$table.'_'.$year;
        $tmp_number = db('system_config')->field('data')->where('id', $next_key)->find();
        if ($tmp_number == null) {
            $tmp_number = 1;
            db('system_config')->insert(['id'=>$next_key, 'data'=>$tmp_number]);
        } else {
            $tmp_number = intval($tmp_number['data']);
        }
        db('system_config')->where('id',$next_key)->update(['id'=>$next_key, 'data'=>$tmp_number+1]);
        $billWaterNo = str_pad($tmp_number, 7, '0', STR_PAD_LEFT);
        $tong_number =  $prev . $area_code . $year . $billWaterNo;
        return $tong_number;
    }
    //退回修改
    public function tuihui(){
        $id = $_POST['id'];
        $data['did'] = $_POST['id'];
        $data['shen_time'] = strtotime($_POST['shenhe_time']);
        $data['shen_peo'] = $_POST['shenhe_peo'];
        if ($_POST['shenhe_yijian'] == ''){
            $this->error('请填写审核意见');
        }else{
            Db::startTrans();
            try {
                $data['shen_yijian'] = $_POST['shenhe_yijian'];
                $data['user_id'] = $this->auth->getUserInfo()['id'];
                $res = Db::name('yijian')->insert($data);
                if($_POST['tong_number']==''){
                    $dataa['status'] = 4;
                    $ress = Db::name('list_one')->where('id',$id)->update($dataa);
                } else{
                    $dataa['status'] = 4;
                    $ress = Db::name('list_three')->where('id',$id)->update($dataa);
                }
                if($ress){
                    Db::commit();
                    $this->success('成功','');
                }else{
                    Db::rollback();
                    $this->error('失败','');
                }
            }catch (Exception $e){
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
    }

}
